//
//  TextView+Extension.swift
//  CosClub
//
//  Created by 沙睿 on 2020/2/14.
//  Copyright © 2020 ios. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import SnapKit

public class TextView: UITextView {
    
    public enum TextViewType {
        case placeholder
        case normal
    }
    
    public override var text: String! {
        didSet {
            let attributedString = NSMutableAttributedString(string: self.text);
            
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 4
            attributedString.addAttribute(NSAttributedString.Key.paragraphStyle,
                                          value: paragraphStyle,
                                          range: NSMakeRange(0, self.text.count))
            self.attributedText = attributedString;
        }
    }
    
    public let placeholderLabel = UILabel.init("说点什么吧~", color:UIColor.app.c3b, fontSize: 12)
    private let disposeBag = DisposeBag()
    
    public convenience init(type: TextViewType, closure: ((_ make: ConstraintMaker) -> Void)? = nil)
    {
        self.init()
        
        switch type {
        case .placeholder:
            addSubview(placeholderLabel)
            var labelClosure = closure
            if labelClosure == nil {
                labelClosure = { (maker) in
                    maker.height.equalTo(16.7)
                    maker.width.equalToSuperview()
                    maker.left.equalToSuperview().offset(8)
                    maker.top.equalToSuperview().offset(6)
                }
            }
            placeholderLabel.snp.makeConstraints(labelClosure!)
        default: break
            
        }
        
        self.rx.text.orEmpty.asObservable()
            .subscribe(onNext: { [weak self](string) in
                self?.placeholderLabel.isHidden = (string.count > 0)
            }).disposed(by: self.disposeBag)
    }
}
